# 异常
# 异常处理是一种艺术，一旦你掌握，会授予你无穷的力量。我将要向你展示我们能处理异常的一些方式。
# 最基本的术语里我们知道了try/except从句。可能触发异常产生的代码会放到try语句块里，而处理异常的代码会在except语句块里实现。这是一个简单的例子：
# try:
#     file = open('test.txt', 'rb')
# except IOError as e:
#     print('An IOError occurred. {}'.format(e.args[-1]))
# 上面的例子里，我们仅仅在处理一个IOError的异常。大部分初学者还不知道的是，我们可以处理多个异常。


# 1. 处理多个异常
# 方法一
try:
    file = open('test.txt', 'rb')
except (IOError, EOFError) as e:
    print("An error occurred. {}".format(e.args[-1]))
# 方法二
try:
    file = open('test.text', 'rb')
except IOError as e:
    print(e)
    raise e
except EOFError as e:
    print(e)
    raise e
# 方法三 捕获所有异常
try:
    file = open('test.text', 'rb')
except Exception as e :
    print(e)
    raise e
# finally从句
try:
    file = open('test.txt', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))
finally:
    print("This would be printed whether or not an exception occurred!")

# try/else从句
try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:
    # 这里的代码只会在try语句里没有触发异常时运行,
    # 但是这里的异常将 *不会* 被捕获
    print('This would only run if no exception occurs. And an error here '
          'would NOT be caught.')
finally:
    print('This would be printed in every case.')